package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.ObjectUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.ObjectUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.domain.po.InteractionQuestion;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.domain.query.ReplyPageQuery;
import com.tianji.learning.domain.vo.ReplyVO;
import com.tianji.learning.domain.query.ReplyPageQuery;
import com.tianji.learning.domain.vo.ReplyVO;
import com.tianji.learning.mapper.InteractionQuestionMapper;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.service.IInteractionQuestionService;
import com.tianji.learning.service.IInteractionReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动问题的回答或评论 服务实现类
 * </p>
 *
 * @author 东哥
 * @since 2024-11-12
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class InteractionReplyServiceImpl extends ServiceImpl<InteractionReplyMapper, InteractionReply> implements IInteractionReplyService {
    private final InteractionQuestionMapper questionService;
    private final UserClient userClient;
    @Override
    @Transactional
    public void addReply(ReplyDTO replyDTO) {
        //新增
        InteractionReply interactionReply = BeanUtils.copyBean(replyDTO, InteractionReply.class);
        interactionReply.setUserId(UserContext.getUser());

        //判断是否回答
        if (ObjectUtils.isEmpty(replyDTO.getAnswerId())) {
            interactionReply.setAnswerId(replyDTO.getAnswerId());
            interactionReply.setTargetReplyId(replyDTO.getTargetReplyId());
            interactionReply.setTargetUserId(replyDTO.getTargetUserId());
            this.save(interactionReply);
            //是则修改问题表最近一次回答的id
            //累加问题表回答次数
            InteractionQuestion interactionQuestion = new InteractionQuestion();
            UpdateWrapper<InteractionQuestion> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", interactionReply.getQuestionId())
                    .setSql("answer_times = answer_times + 1")
                    .setSql("latest_answer_id = " + interactionReply.getId());
            questionService.update(interactionQuestion,wrapper);


        }else {
            //否则累加回答下评论次数
            InteractionQuestion interactionQuestion = new InteractionQuestion();
            UpdateWrapper<InteractionQuestion> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", interactionReply.getQuestionId())
                    .setSql("answer_times = answer_times + 1");
            questionService.update(interactionQuestion,wrapper);
            this.save(interactionReply);
        }


        //判断是否学生
        if (replyDTO.getIsStudent()) {
            //是则修改标记问腿为未查看
            InteractionQuestion interactionQuestion = new InteractionQuestion();
            UpdateWrapper<InteractionQuestion> wrapper = new UpdateWrapper<>();
            wrapper.eq("id", replyDTO.getQuestionId())
                    .setSql("status=false");
            questionService.update(interactionQuestion,wrapper);
        }

    }

    @Override
    public PageDTO<ReplyVO> QueryReply(ReplyPageQuery pageQuery) {
        Long answerId = pageQuery.getAnswerId();
        Long questionId = pageQuery.getQuestionId();
        if (ObjectUtils.isEmpty(answerId) && ObjectUtils.isEmpty(questionId)) {
            return PageDTO.empty(0L,0L);
        }
        List<ReplyVO>list = new ArrayList<>();

        if (ObjectUtils.isEmpty(answerId)) {
            //查询回复
            Page<InteractionReply> page = this.lambdaQuery()
                    .eq(InteractionReply::getQuestionId, questionId)
                    .eq(InteractionReply::getHidden, false)
                    .page(pageQuery.toMpPageDefaultSortByCreateTimeDesc());
            List<InteractionReply> records = page.getRecords();
            if (ObjectUtils.isEmpty(records)) {
                return PageDTO.empty(0L,0L);
            }

            Map<Long, UserDTO> userDTOMap = finddate(records);
            if(userDTOMap==null){
                return PageDTO.empty(0L,0L);
            }

            //组装
            for (InteractionReply record : records) {
                ReplyVO replyVO = BeanUtils.copyBean(record, ReplyVO.class);
                if(!record.getAnonymity()){
                    replyVO.setUserName(userDTOMap.get(record.getUserId()).getName());
                    replyVO.setUserIcon(userDTOMap.get(record.getUserId()).getIcon());
                }
                list.add(replyVO);
            }
            return PageDTO.of(page, list);
        }
        //查询回复
        Page<InteractionReply> page = this.lambdaQuery()
                .eq(InteractionReply::getAnswerId, answerId)
                .eq(InteractionReply::getHidden, false)
                .page(pageQuery.toMpPageDefaultSortByCreateTimeDesc());
        List<InteractionReply> records = page.getRecords();
        if (ObjectUtils.isEmpty(records)) {
            return PageDTO.empty(0L,0L);
        }

        Map<Long, UserDTO> userDTOMap = finddate(records);
        if(userDTOMap==null){
            return PageDTO.empty(0L,0L);
        }

        //组装

        for (InteractionReply record : records) {
            ReplyVO replyVO = BeanUtils.copyBean(record, ReplyVO.class);
            if(!record.getAnonymity()){
                replyVO.setUserName(userDTOMap.get(record.getUserId()).getName());
                replyVO.setUserIcon(userDTOMap.get(record.getUserId()).getIcon());
            }
            InteractionReply byId = getById(record.getAnswerId());
            if (!byId.getAnonymity()) {
                replyVO.setTargetUserName(userDTOMap.get(record.getTargetUserId()).getName());
            }
            list.add(replyVO);
        }



        return PageDTO.of(page, list);
    }

    public Map<Long, UserDTO>finddate(List<InteractionReply> records){
        List<Long> ids = records.stream().map(u -> u.getUserId()).collect((Collectors.toList()));
        List<Long> collect = records.stream().map(u -> u.getTargetUserId()).collect((Collectors.toList()));
        if(ObjectUtils.isNotEmpty(collect)){
            for (Long l : collect) {
                ids.add(l);
            }
        }
        List<UserDTO> userDTOS = userClient.queryUserByIds(ids);
        Map<Long, UserDTO> userDTOMap = userDTOS.stream().collect(Collectors.toMap(UserDTO::getId, Function.identity()));
        if (ObjectUtils.isEmpty(userDTOS)) {
            return null;
        }
        return userDTOMap;
    }


    /**
     *  管理员查询回复列表
     * @param replyPageQuery
     * @return
     */
    @Override
    public PageDTO<ReplyVO> pageAdminList(ReplyPageQuery replyPageQuery) {
         Long questionId = replyPageQuery.getQuestionId();
         Long answerId = replyPageQuery.getAnswerId();
        if (ObjectUtils.isEmpty(questionId) && ObjectUtils.isEmpty(answerId)) {
            throw new BadRequestException("问题ID和回答ID不能同时为空！");
        }
        Page<InteractionReply> page = this.lambdaQuery()
                .eq(ObjectUtils.isNotEmpty(questionId), InteractionReply::getQuestionId, questionId)
                .eq(ObjectUtils.isNotEmpty(answerId), InteractionReply::getAnswerId, answerId)
                .eq(ObjectUtils.isEmpty(answerId), InteractionReply::getAnswerId, 0L)
                .page(replyPageQuery.toMpPageDefaultSortByCreateTimeDesc());
         List<InteractionReply> records = page.getRecords();
         if(ObjectUtils.isEmpty(records)){
              return  PageDTO.empty(page);
         }
          //回答者id集合和被评论的用户id
        Set<Long> userids=new HashSet<>();
        for (InteractionReply record : records) {
             userids.add(record.getUserId());
             userids.add(record.getTargetUserId());
        }
        List<UserDTO> userInfoList = userClient.queryUserByIds(userids);
        Map<Long, UserDTO> userInfoMap = new HashMap<>(userids.size());
        if (ObjectUtils.isNotEmpty(userInfoList)) {
            userInfoMap = userInfoList.stream().collect(Collectors.toMap(UserDTO::getId, Function.identity()));
        }
        List<ReplyVO> replyVOS = new ArrayList<>();
        //回答者的
          for (InteractionReply record : records) {
               ReplyVO replyVO = BeanUtils.copyProperties(record, ReplyVO.class);
               //上级的回复id
               //收集评论数量
               Long answerId1 = record.getId();
               Integer count = this.lambdaQuery()
                      .eq(InteractionReply::getAnswerId, answerId1)
                      .count();
               if(ObjectUtils.isNotEmpty(count)&&count>0){
                   replyVO.setReplyTimes(count);
               }else{
                   replyVO.setReplyTimes(0);
               }
               UserDTO userDTO = userInfoMap.get(record.getUserId());
               replyVO.setUserName(userDTO.getName());
               replyVO.setUserIcon(userDTO.getIcon());
               UserDTO userDTO1 = userInfoMap.get(record.getTargetUserId());
               replyVO.setTargetUserName(userDTO1.getName());
              replyVOS.add(replyVO);
          }
        return PageDTO.of(page,replyVOS);
    }

    /**
     * 管理端显示或隐藏评论
     * @param id
     * @param status
     */
    @Override
    public void showOrHide(Long id, Boolean status) {
         InteractionReply one = this.lambdaQuery()
                .eq(InteractionReply::getId, id)
                .one();
          if(ObjectUtils.isEmpty(one)){
              return;
          }
        one.setHidden(status);
        this.updateById(one);
         List<InteractionReply> list = this.lambdaQuery()
                .eq(InteractionReply::getAnswerId, id)
                .list();
          if(ObjectUtils.isEmpty(list)){
              for (InteractionReply interactionReply : list) {
                  interactionReply.setHidden(status);
              }
              updateBatchById(list);
          }
    }
}
